package cn.itcast.shopping;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class BuyServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		String id = request.getParameter("id");

		Book book = (Book) Db.getAll().get(id);

		//从session 得到用户用于保存所有书的集合 (购物车)

		HttpSession session = request.getSession();

		List<Book> list= (List<Book>) session.getAttribute("list");

		if (list==null) {
			ArrayList<Book> books = new ArrayList<Book>();
			session.setAttribute("list", books);
		}

		list.add(book);

		//		response.sendRedirect("/day07/ListCarServlet");


		//		response.sendRedirect(request.getContextPath()+"/ListCarServlet");

		String url = response.encodeRedirectURL(request.getContextPath()+"/ListCarServlet");
		response.sendRedirect(url);






	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
		response.setContentType("text/html;charset=UTF-8");

	}

}
